import lcd_bus
from micropython import const
import machine
import lcd_utils

_BUFFER_SIZE = const(30720)

# 创建SPI总线对象
spi_bus = machine.SPI.Bus(
    host=1,
    mosi=6,
    miso=-1,
    sck=7,    
)

# 创建显示屏的SPI通信对象
display_bus = lcd_bus.SPIBus(
    spi_bus=spi_bus,
    freq=40000000,
    dc=4,
    cs=5
)

fb1 = display_bus.allocate_framebuffer(_BUFFER_SIZE, lcd_bus.MEMORY_INTERNAL | lcd_bus.MEMORY_DMA)
fb2 = display_bus.allocate_framebuffer(_BUFFER_SIZE, lcd_bus.MEMORY_INTERNAL | lcd_bus.MEMORY_DMA)

import ili9341  # NOQA
import lvgl as lv  # NOQA

ili9341.ILI9341._ORIENTATION_TABLE = (
    0x0,
    0x60,
    0x40 | 0x80,
    0x20 | 0x40 | 0x80
)

# 创建显示屏对象
display = ili9341.ILI9341(
    data_bus=display_bus,
    frame_buffer1=fb1,
    frame_buffer2=fb2,
    display_width=320,
    display_height=240,
    backlight_pin=47,
    color_space=lv.COLOR_FORMAT.RGB565,
    color_byte_order=ili9341.BYTE_ORDER_BGR,
    rgb565_byte_swap=True,
)

import i2c
import task_handler
import gt911, pointer_framework

# 初始化显示屏
display.init(2)

# 定义触摸屏的I2C通信参数
i2c_bus = i2c.I2C.Bus(host=0, scl=18, sda=8, freq=400000, use_locks=False)
touch_dev = i2c.I2C.Device(bus=i2c_bus, dev_id=0x5D, reg_bits=gt911.BITS)

# 创建触摸屏设备对象
indev = gt911.GT911(touch_dev,startup_rotation=pointer_framework.lv.DISPLAY_ROTATION._180)#
if indev.hw_size != (320, 240):
    fw = indev.firmware_config
    fw.width = 320
    fw.height = 240
    fw.save()
    del fw

# 打开屏幕背光
display.set_backlight(1)

# 启用输入优先级
indev.enable_input_priority()

# 旋转显示
display.set_rotation(lv.DISPLAY_ROTATION._180)

# 创建一个任务处理器实例
th = task_handler.TaskHandler()